import React, { useEffect, useState } from "react";
import { 
  Col, 
  Row, 
  Card, 
  Table, 
  Button, 
  Form, 
  Input, 
  Select, 
  Upload, 
  message,
  Affix,
  Dropdown,
  Menu,
  List,
  Avatar,
  Tag,
  Drawer,
  Tabs,
  Descriptions,
  Modal,
  Space,
  Pagination,
  Tag as AntdTag
} from "antd";
import * as Icon from '@ant-design/icons';
import { UploadOutlined, CloseOutlined, PlusOutlined, DownOutlined, UserOutlined ,DeleteOutlined ,DownloadOutlined,
  EyeOutlined } from '@ant-design/icons';
import './home.css'
import { fetchUserInfo, uploadTorrent, createTorrent, getFollowsList, getFansList,deFollowUser,fetchUserTorrents,
  downloadTorrent,getPromotionRules  } from "../../store/modules/userStore";
import { useDispatch } from "react-redux";
import { useNavigate } from 'react-router-dom';

const { Option } = Select;
const { TabPane } = Tabs;

  // 分类选项
  const categories = [
    { id: 1, name: '电影' },
    { id: 2, name: '电视剧' },
    { id: 3, name: '动漫' },
    { id: 4, name: '音乐' },
    { id: 5, name: '游戏' },
    { id: 6, name: '软件' },
    { id: 7, name: '纪录片' },
    { id: 8, name: '体育' },
    { id: 9, name: '电子书' },
    { id: 99, name: '其他' }
    
  ];

// 动态获取icon
const iconToElement = (name) => React.createElement(Icon[name])

const Home = () => {

     const [torrentPagination, setTorrentPagination] = useState({
        current: 1,
        pageSize: 3, // 每页3个种子
        total: 0
    });
    const userImg = require("../../assets/images/user_default.png");
    const dispatch = useDispatch();
    const [userInfo, setUserInfo] = useState({});
     const [userTorrents, setUserTorrents] = useState([]);
    const [loadingTorrents, setLoadingTorrents] = useState(false);
    const [selectedTorrent, setSelectedTorrent] = useState(null);
    const [torrentModalVisible, setTorrentModalVisible] = useState(false);
    const [showUploadForm, setShowUploadForm] = useState(false);
    const [uploadType, setUploadType] = useState('upload');
    const [form] = Form.useForm();
    const [fileList, setFileList] = useState([]);
    const [listVisible, setListVisible] = useState(false);
    const [followsList, setFollowsList] = useState([]);
    const [fansList, setFansList] = useState([]);
    const [loading, setLoading] = useState({ follows: false, fans: false });
    const [activeTab, setActiveTab] = useState('follows');
     const navigate = useNavigate();
     const [promotionRules, setPromotionRules] = useState([]);
    const [loadingRules, setLoadingRules] = useState(false);


    
    

    useEffect(() => {
         // 组件挂载时禁用滚动
    document.body.style.overflow = 'hidden';
        dispatch(fetchUserInfo()).then(res => {
            setUserInfo(res.data);
            localStorage.setItem('userId', res.data.userId);
            localStorage.setItem('passKey', res.data.passKey);
            // 获取用户种子列表
            fetchMyTorrents(res.data.userId);
            // 获取促销规则
             fetchPromotionRules();
        }).catch(err => {
            console.log("主页获取信息错误：", err);
        });
        // 组件卸载时恢复滚动
    return () => {
      document.body.style.overflow = 'auto';
    };
    }, []);
    // 添加获取促销规则的函数
        const fetchPromotionRules = async () => {
            setLoadingRules(true);
            try {
                const res = await dispatch(getPromotionRules());
                    setPromotionRules(res);
  
            } catch (error) {

            } finally {
                setLoadingRules(false);
            }
        };
    // 修改 fetchMyTorrents 函数
const fetchMyTorrents = (userId) => {
    setLoadingTorrents(true);
    const { current, pageSize } = torrentPagination;
    dispatch(fetchUserTorrents({ 
        userId,
        page: current,
        size: pageSize
    }))
        .then(res => {
            if (res.code === 0 && res.data) {
                setUserTorrents(res.data.list || []);
                setTorrentPagination(prev => ({
                    ...prev,
                    total: res.data.total || 0
                }));
            } else {
                // 处理没有种子的情况
                setUserTorrents([]);
                setTorrentPagination(prev => ({
                    ...prev,
                    total: 0
                }));
                if (res.code !== 1) { // 如果不是"没有种子"的预期错误，显示错误消息
                    message.info(res.msg || '获取种子列表失败');
                }
            }
        })
        .catch(err => {

        })
        .finally(() => {
            setLoadingTorrents(false);
        });
};

    // 处理分页变化
    const handleTorrentPageChange = (page, pageSize) => {
        setTorrentPagination({
            current: page,
            pageSize,
            total: torrentPagination.total
        });
    };

    useEffect(() => {
        if (userInfo?.userId) {
            fetchMyTorrents(userInfo.userId);
        }
    }, [userInfo?.userId, torrentPagination.current, torrentPagination.pageSize]);

    // 处理下载
    const handleDownload = async (torrentId) => {
        try {
            const res = await dispatch(downloadTorrent({
                id: torrentId,
                passKey: localStorage.getItem('passKey')
            }));
            
            if (res.code === 0) {
                const downloadUrl = res.data;
                const link = document.createElement('a');
                link.href = downloadUrl;
                link.download = '';
                link.style.display = 'none';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                message.success('开始下载种子文件');
            } else {
                message.error(res.msg || '下载失败');
            }
        } catch (err) {
            console.error('下载错误:', err);
            message.error('下载失败');
        }
    };

    // 显示种子详情
    const showTorrentDetail = (record) => {
        setSelectedTorrent(record);
        setTorrentModalVisible(true);
    };

    // 格式化文件大小
    const formatSize = (bytes) => {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    };

    // 用户种子列表列定义
    const torrentColumns = [
        {
            title: '标题',
            dataIndex: 'title',
            key: 'title',
            render: (text, record) => (
                <div className="torrent-title">
                    <span>{text}</span>
                    {record.freeleech && (
                        <AntdTag color="green" style={{ marginLeft: 8 }}>免费</AntdTag>
                    )}
                </div>
            ),
        },
        {
            title: '大小',
            dataIndex: 'fileSize',
            key: 'fileSize',
            width: 120,
            render: (size) => formatSize(size),
        },
        {
            title: '分类',
            dataIndex: 'category',
            key: 'category',
            width: 100,
            render: (category) => (
                categories.find(c => c.id === category)?.name || '未知'
            )
        },
        {
            title: '上传时间',
            dataIndex: 'uploadTime',
            key: 'uploadTime',
            width: 180,
            render: (time) => new Date(time).toLocaleString(),
        },
        {
            title: '操作',
            key: 'action',
            width: 150,
            render: (_, record) => (
                <Space size="middle">
                    <Button 
                        type="link" 
                        icon={<EyeOutlined />} 
                        onClick={() => showTorrentDetail(record)}
                    >
                        详情
                    </Button>
                    <Button 
                        type="link" 
                        icon={<DownloadOutlined />} 
                        onClick={() => handleDownload(record.id)}
                    >
                        下载
                    </Button>
                </Space>
            ),
        }
    ];

    // 删除关注用户
    const handleUnfollow = async (userId) => {
        try {
            const res = await dispatch(deFollowUser(userId));
            if (res.code === 0) {
                message.success('取消关注成功');
                // 更新关注列表
                setFollowsList(followsList.filter(user => user.userId !== userId));
                // 更新用户信息中的关注数
                setUserInfo({
                    ...userInfo,
                    follows: userInfo.follows - 1
                });
            } else {
                message.error(res.msg || '取消关注失败');
            }
        } catch (error) {
            console.error('取消关注错误:', error);
            message.error('取消关注失败');
        }
    };
    // 获取关注列表
    const fetchFollows = async () => {
        setLoading({...loading, follows: true});
        try {
            const res = await dispatch(getFollowsList());
            if (res.code === 0) {
                setFollowsList(res.data);
                setActiveTab('follows');
                setListVisible(true);
            } else {
                message.error(res.msg || '获取关注列表失败');
            }
        } catch (error) {
            console.error('获取关注列表错误:', error);
            message.error('获取关注列表失败');
        } finally {
            setLoading({...loading, follows: false});
        }
    };

    // 获取粉丝列表
    const fetchFans = async () => {
        setLoading({...loading, fans: true});
        try {
            const res = await dispatch(getFansList());
            if (res.code === 0) {
                setFansList(res.data);
                setActiveTab('fans');
                setListVisible(true);
            } else {
                message.error(res.msg || '获取粉丝列表失败');
            }
        } catch (error) {
            console.error('获取粉丝列表错误:', error);
            message.error('获取粉丝列表失败');
        } finally {
            setLoading({...loading, fans: false});
        }
    };

    // 标签页切换时的处理
    const handleTabChange = async (key) => {
        setActiveTab(key);
        if (key === 'follows' && followsList.length === 0) {
            await fetchFollows();
        } else if (key === 'fans' && fansList.length === 0) {
            await fetchFans();
        }
    };

    // 上传菜单
    const uploadMenu = (
        <Menu onClick={({ key }) => {
            setUploadType(key);
            setShowUploadForm(true);
        }}>
            <Menu.Item key="upload" icon={<UploadOutlined />}>
                上传文件
            </Menu.Item>
            <Menu.Item key="create" icon={<PlusOutlined />}>
                创建种子
            </Menu.Item>
        </Menu>
    );
            // 添加辅助函数
        const getRuleTitle = (rule) => {
            const conditionMap = {
                'time': '时间规则',
                'seeders': '做种人数规则',
                'holiday': '假期规则'
            };
            return conditionMap[rule.conditionType] || '促销规则';
        };

        const getRuleDescription = (rule) => {
            const threshold = rule.threshold || 24.0;
            
            if (rule.conditionType === 'time') {
                return `创建${threshold}小时内的种子`;
            } else if (rule.conditionType === 'seeders') {
                return `做种人数少于${threshold}的种子`;
            } else if (rule.conditionType === 'holiday') {
                return '假期期间所有种子';
            }
            return '';
        };

        const getRuleTagColor = (rule) => {
            const actionColors = {
                'free_download': 'green',
                'upload_boost': 'blue',
                'download_discount': 'orange'
            };
            return actionColors[rule.actionType] || 'default';
        };

        const getRuleTagText = (rule) => {
            if (rule.actionType === 'free_download') {
                return '免费下载';
            } else if (rule.actionType === 'upload_boost') {
                return `上传量×${rule.value}`;
            } else if (rule.actionType === 'download_discount') {
                return `下载量${rule.value * 10}折`;
            }
            return '';
        };
    // 创建种子时检查文件类型
    const beforeUpload = (file) => {
        if (uploadType === 'create' && !file.name.endsWith('.torrent')) {
            message.error('创建种子必须选择.torrent文件');
            return Upload.LIST_IGNORE;
        }
        return true;
    };

    const handleUpload = async () => {
        try {
            const values = await form.validateFields();
            if (fileList.length === 0) {
                message.error('请选择文件');
                return;
            }

            if (uploadType === 'create' && !fileList[0].name.endsWith('.torrent')) {
                message.error('创建种子必须选择.torrent文件');
                return;
            }
     
            const formData = new FormData();
            formData.append('torrentFile', fileList[0].originFileObj);
            formData.append('title', values.title);
            formData.append('description', values.description);
            formData.append('categoryId', values.categoryId);
            formData.append('isAnonymous', values.isAnonymous);
            formData.append('isFreeleech', values.isFreeleech);

            const action = uploadType === 'upload' ? uploadTorrent : createTorrent;
            const res = await dispatch(action(formData));
            if (res.code === 0) {
                message.success(uploadType === 'upload' ? '文件上传成功' : '种子创建成功');
                setShowUploadForm(false);
                form.resetFields();
                setFileList([]);
            } else {
                message.error(res.message || '操作失败');
            }
        } catch (err) {
            console.error('上传错误:', err);
            message.error('操作失败');
        }
    };

    const handleFileChange = (info) => {
        let newFileList = [...info.fileList];
        newFileList = newFileList.slice(-1);
        setFileList(newFileList);
    };

    // 统计数据
    const countData = [
        {
            "name": "总上传资源数量",
            "value": userInfo?.uploaded_delta || 0,
            "icon": "CheckCircleOutlined",
            "color": "#2ec7c9"
        },
        {
            "name": "总下载资源数量",
            "value": userInfo?.downloaded_delta || 0,
            "icon": "CheckCircleOutlined",
            "color": "#ffb980"
        },
        {
            "name": "邀请用户数量",
            "value": "5",
            "icon": "ClockCircleOutlined",
            "color": "#5ab1ef"
        },
        {
            "name": "",
            "value": "",
            "icon": "CheckCircleOutlined",
            "color":"#2ec7c9"
        },
        {
            "name": "",
            "value": "",
            "icon": "CheckCircleOutlined",
            "color":"#ffb980"
        },
        {
            "name": "",
            "value": "",
            "icon": "ClockCircleOutlined",
            "color":"#5ab1ef"
        }
    ];

    
  // 渲染关注列表项
  const renderFollowItem = (item) => (
    <List.Item
      actions={[
        <Button 
          type="text" 
          icon={<DeleteOutlined />} 
          onClick={(e) => {
            e.stopPropagation();
            handleUnfollow(item.userId);
          }}
          danger
        />
      ]}
    >
      <List.Item.Meta
        avatar={
          <Avatar 
            src={item.avatar} 
            icon={<UserOutlined />}
            onClick={(e) => {
              e.stopPropagation();
              navigate(`/user/${item.userId}`);
            }}
            style={{ cursor: 'pointer' }}
          />
        }
        title={
          <a onClick={() => navigate(`/user/${item.userId}`)}>
            {item.username}
          </a>
        }
        description={item.address || '暂无地址'}
      />
      <Tag color="blue">Lv.{item.level}</Tag>
    </List.Item>
  );

  // 粉丝列表项（类似，去掉删除按钮）
  const renderFanItem = (item) => (
    <List.Item>
      <List.Item.Meta
        avatar={
          <Avatar 
            src={item.avatar} 
            icon={<UserOutlined />}
            onClick={() => navigate(`/user/${item.userId}`)}
            style={{ cursor: 'pointer' }}
          />
        }
        title={
          <a onClick={() => navigate(`/user/${item.userId}`)}>
            {item.username}
          </a>
        }
        description={item.address || '暂无地址'}
      />
      <Tag color="blue">Lv.{item.level}</Tag>
    </List.Item>
  );


    return (

        <Row className="home">
            <Col span={8}>
                <Card hoverable>
                    <div className="user">
                        <img src={userInfo?.avatar || userImg} alt="用户头像" />
                        <div className="user-info">
                            <p className="name">{userInfo?.username || "暂无username"}</p>
                            <p className="access">{userInfo?.role || "暂无role"}</p>
                        </div>
                    </div>
                    <div className="login-info">
                        <p>ADDRESS：<span>{userInfo?.address || "暂无address"}</span></p>
                        <p>EMAIL：<span>{userInfo?.email || "暂无email"}</span></p>
                         <p>
                                FOLLOW：
                                <span>{userInfo?.follows || "暂无关注"}</span>
                                <Button 
                                    type="link" 
                                    size="small" 
                                    onClick={fetchFollows}
                                    loading={loading.follows}
                                >
                                    查看关注
                                </Button>
                            </p>
                            <p>
                                FAN：
                                <span>{userInfo?.fans || "暂无粉丝"}</span>
                                <Button 
                                    type="link" 
                                    size="small" 
                                    onClick={fetchFans}
                                    loading={loading.fans}
                                >
                                    查看粉丝
                                </Button>
                            </p>
                    </div>
                </Card>
                
<Card 
    title="我的上传" 
    style={{ marginTop: 16 }}
    loading={loadingTorrents}
>
    {userTorrents.length > 0 ? (
        <>
            <Table
                columns={torrentColumns}
                dataSource={userTorrents}
                rowKey="id"
                pagination={false}
                size="small"
            />
            <div style={{ marginTop: 16, textAlign: 'center' }}>
                <Pagination
                    current={torrentPagination.current}
                    pageSize={torrentPagination.pageSize}
                    total={torrentPagination.total}
                    onChange={handleTorrentPageChange}
                    showSizeChanger={false}
                    showQuickJumper={false}
                    showTotal={total => `共 ${total} 条`}
                    size="small"
                    simple
                />
            </div>
        </>
    ) : (
        <div style={{ 
            padding: '24px 0', 
            textAlign: 'center',
            color: 'rgba(0, 0, 0, 0.25)'
        }}>
            暂无上传的种子
        </div>
    )}
</Card>
            </Col>
            <Col span={16}>
               
                <Card 
                        title="促销规则" 
                        style={{ marginTop: 16 }}
                        loading={loadingRules}
                        className="promotion-rule-list"
                    >
                        {/* 促销规则列表 */}
                        <List
                            dataSource={promotionRules.filter(rule => rule.isActive)}
                            renderItem={rule => (
                                <List.Item>
                                    <List.Item.Meta
                                        title={getRuleTitle(rule)}
                                        description={getRuleDescription(rule)}
                                    />
                                    <Tag color={getRuleTagColor(rule)}>
                                        {getRuleTagText(rule)}
                                    </Tag>
                                </List.Item>
                            )}
                        />
                    </Card>
            </Col>
            {/* 种子详情模态框 */}
            <Modal
                title="种子详情"
                width={700}
                visible={torrentModalVisible}
                onCancel={() => setTorrentModalVisible(false)}
                footer={[
                    <Button 
                        key="download" 
                        type="primary" 
                        icon={<DownloadOutlined />}
                        onClick={() => selectedTorrent && handleDownload(selectedTorrent.id)}
                    >
                        下载种子
                    </Button>,
                    <Button key="close" onClick={() => setTorrentModalVisible(false)}>
                        关闭
                    </Button>
                ]}
            >
                {selectedTorrent && (
                    <Descriptions bordered column={2}>
                        <Descriptions.Item label="标题" span={2}>
                            {selectedTorrent.title}
                            {selectedTorrent.freeleech && (
                                <AntdTag color="green" style={{ marginLeft: 8 }}>免费</AntdTag>
                            )}
                        </Descriptions.Item>
                        <Descriptions.Item label="描述">{selectedTorrent.description}</Descriptions.Item>
                        <Descriptions.Item label="文件大小">{formatSize(selectedTorrent.fileSize)}</Descriptions.Item>
                        <Descriptions.Item label="文件数量">{selectedTorrent.fileCount}</Descriptions.Item>
                        <Descriptions.Item label="分类">
                            {categories.find(c => c.id === selectedTorrent.category)?.name || '未知'}
                        </Descriptions.Item>
                        <Descriptions.Item label="上传时间">
                            {new Date(selectedTorrent.uploadTime).toLocaleString()}
                        </Descriptions.Item>
                    </Descriptions>
                )}
            </Modal>
 {/* 用户列表抽屉 */}
        <Drawer
            title="用户列表"
            placement="right"
            width={400}
            onClose={() => setListVisible(false)}
            visible={listVisible}
            bodyStyle={{ padding: 0 }}
        >
            <Tabs 
                activeKey={activeTab} 
                onChange={handleTabChange}
                centered
            >
                <TabPane tab="我的关注" key="follows">
                    <List
                        dataSource={followsList}
                        loading={loading.follows}
                        renderItem={renderFollowItem}
                    />
                </TabPane>
                <TabPane tab="我的粉丝" key="fans">
                    <List
                        dataSource={fansList}
                        loading={loading.fans}
                        renderItem={renderFanItem}
                    />
                </TabPane>
            </Tabs>
        </Drawer>

            {/* 右下角悬浮上传按钮和表单 */}
            <Affix style={{ position: 'fixed', right: 24, bottom: 24 }}>
                {!showUploadForm ? (
                    <Dropdown overlay={uploadMenu} trigger={['hover']}>
                        <Button 
                            type="primary" 
                            shape="circle" 
                            size="large"
                            icon={<UploadOutlined />}
                            className="floating-upload-btn"
                        />
                    </Dropdown>
                ) : (
                    <Card 
                        title={uploadType === 'upload' ? '上传文件' : '创建种子'} 
                        className="upload-form-card"
                        extra={
                            <CloseOutlined 
                                onClick={() => {
                                    setShowUploadForm(false);
                                    form.resetFields();
                                    setFileList([]);
                                }} 
                            />
                        }
                    >
                        <Form form={form} layout="vertical">
                            <Form.Item
                                name="torrentFile"
                                label={uploadType === 'upload' ? '选择文件' : '选择种子文件(.torrent)'}
                                rules={[{ required: true, message: '请选择文件' }]}
                            >
                                <Upload
                                    beforeUpload={beforeUpload}
                                    onChange={handleFileChange}
                                    fileList={fileList}
                                    maxCount={1}
                                    accept={uploadType === 'create' ? '.torrent' : undefined}
                                >
                                    <Button icon={<UploadOutlined />}>
                                        {uploadType === 'upload' ? '选择文件' : '选择.torrent文件'}
                                    </Button>
                                </Upload>
                            </Form.Item>
                            <Form.Item
                                name="title"
                                label="标题"
                                rules={[{ required: true, message: '请输入标题' }]}
                            >
                                <Input placeholder="请输入标题" />
                            </Form.Item>
                            <Form.Item
                                name="description"
                                label="描述"
                                rules={[{ required: true, message: '请输入描述' }]}
                            >
                                <Input.TextArea rows={4} placeholder="请输入描述" />
                            </Form.Item>
                            <Row gutter={16}>
                                <Col span={8}>
                                    <Form.Item
                                        name="categoryId"
                                        label="分类"
                                        rules={[{ required: true, message: '请选择分类' }]}
                                    >
                                        <Select placeholder="请选择分类">
                                            <Option value={1}>电影</Option>
                                            <Option value={2}>电视剧</Option>
                                            <Option value={3}>动漫</Option>
                                            <Option value={4}>音乐</Option>
                                            <Option value={5}>游戏</Option>
                                            <Option value={6}>软件</Option>
                                            <Option value={7}>纪录片</Option>
                                            <Option value={8}>体育</Option>
                                            <Option value={9}>电子书</Option>
                                            <Option value={99}>其他</Option>
                                            
                                        </Select>
                                    </Form.Item>
                                </Col>
                                <Col span={8}>
                                    <Form.Item
                                        name="isAnonymous"
                                        label="是否匿名"
                                        rules={[{ required: true, message: '请选择是否匿名' }]}
                                    >
                                        <Select placeholder="请选择是否匿名">
                                            <Option value={true}>是</Option>
                                            <Option value={false}>否</Option>
                                        </Select>
                                    </Form.Item>
                                </Col>
                                <Col span={8}>
                                    <Form.Item
                                        name="isFreeleech"
                                        label="是否免费"
                                        rules={[{ required: true, message: '请选择是否免费' }]}
                                    >
                                        <Select placeholder="请选择是否免费">
                                            <Option value={true}>是</Option>
                                            <Option value={false}>否</Option>
                                        </Select>
                                    </Form.Item>
                                </Col>
                            </Row>
                            <Button 
                                type="primary" 
                                onClick={handleUpload}
                                style={{ marginTop: 16, width: '100%' }}
                            >
                                {uploadType === 'upload' ? '上传文件' : '创建种子'}
                            </Button>
                        </Form>
                    </Card>
                )}
            </Affix>
        </Row>
    );
};

export default Home;